package servlet.admin;

import dao.OwnerDao;
import entity.Admin;
import entity.Owner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/admin/owner/*")
public class OwnerServlet extends HttpServlet {
    private OwnerDao ownerDao = new OwnerDao();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();

        // 检查管理员登录状态
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/adminLogin.jsp");
            return;
        }

        try {
            switch (action) {
                case "/delete":
                    deleteOwner(request, response);
                    break;
                case "/edit":
                    showEditForm(request, response);
                    break;
                case "/view":
                    viewOwner(request, response);
                    break;
                default:
                    response.sendRedirect(request.getContextPath() + "/admin/ownerManage.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("/admin/ownerManage.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();

        // 检查管理员登录状态
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/adminLogin.jsp");
            return;
        }

        try {
            switch (action) {
                case "/add":
                    addOwner(request, response);
                    break;
                case "/update":
                    updateOwner(request, response);
                    break;
                default:
                    response.sendRedirect(request.getContextPath() + "/admin/ownerManage.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("/admin/ownerManage.jsp").forward(request, response);
        }
    }

    private void deleteOwner(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        ownerDao.deleteOwner(id);
        response.sendRedirect(request.getContextPath() + "/admin/ownerManage.jsp");
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Owner owner = ownerDao.getOwnerById(id);
        if (owner != null) {
            request.setAttribute("owner", owner);
            request.getRequestDispatcher("/admin/editOwner.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/admin/ownerManage.jsp");
        }
    }

    private void viewOwner(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Owner owner = ownerDao.getOwnerById(id);
        if (owner != null) {
            request.setAttribute("owner", owner);
            request.getRequestDispatcher("/admin/viewOwner.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/admin/ownerManage.jsp");
        }
    }

    private void addOwner(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Owner owner = new Owner();
        owner.setUsername(request.getParameter("username"));
        owner.setPassword(request.getParameter("password"));
        owner.setName(request.getParameter("name"));
        owner.setBuilding(request.getParameter("building"));
        owner.setUnit(request.getParameter("unit"));
        owner.setRoom(request.getParameter("roomNumber"));
        owner.setType(request.getParameter("type").equals("1") ? "1" : "2");
        owner.setPlateNumber(request.getParameter("plateNumber"));
        owner.setPhone(request.getParameter("phone"));
        try {
            Date checkInDate = sdf.parse(request.getParameter("checkInDate"));
            owner.setCreateTime(checkInDate);
        } catch (Exception e) {
            owner.setCreateTime(new Date());
        }

        ownerDao.addOwner(owner);
        response.sendRedirect(request.getContextPath() + "/admin/ownerManage.jsp");
    }

    private void updateOwner(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("开始更新业主信息");
        try {
            Owner owner = new Owner();
            owner.setId(Integer.parseInt(request.getParameter("id")));
            owner.setUsername(request.getParameter("username"));
            owner.setPassword(request.getParameter("password"));
            owner.setName(request.getParameter("name"));
            owner.setBuilding(request.getParameter("building"));
            owner.setUnit(request.getParameter("unit"));
            owner.setRoom(request.getParameter("roomNumber"));
            owner.setType(request.getParameter("type"));
            owner.setPlateNumber(request.getParameter("plateNumber"));
            owner.setPhone(request.getParameter("phone"));

            String dateStr = request.getParameter("checkInDate");
            System.out.println("接收到的日期字符串: " + dateStr);

            try {
                Date checkInDate = sdf.parse(dateStr);
                owner.setCreateTime(checkInDate);
                System.out.println("解析后的日期: " + checkInDate);
            } catch (Exception e) {
                System.out.println("日期解析失败，使用当前时间");
                owner.setCreateTime(new Date());
            }

            System.out.println("准备调用DAO更新");
            ownerDao.updateOwner(owner);
            System.out.println("更新完成");

            response.sendRedirect(request.getContextPath() + "/admin/ownerManage.jsp");
        } catch (Exception e) {
            System.out.println("更新失败: " + e.getMessage());
            e.printStackTrace();
            throw new ServletException("更新业主信息失败", e);
        }
    }
}